package com.lili.userservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lili.userservice.entity.TbUser;
import com.lili.userservice.listemer.DataEasyExcelListener;
import com.lili.userservice.mapper.TbUserMapper;
import com.lili.userservice.service.TbUserService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lili
 * @since 2020-07-20
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Override
    public List<TbUser> findUserAndDept(Integer current, Integer size) {
        return this.baseMapper.findUserAndDept(current,size);
    }

    @Override
    public Integer findUserAndDeptCount() {
        return this.baseMapper.findUserAndDeptCount();
    }

    @Override
    public Page<TbUser> findUserPage(Page<TbUser> page, QueryWrapper<TbUser> wrapper) {
        return this.baseMapper.findUserPage(page,wrapper);
    }

    /**
     * 出用户信息
     * @param response
     * @throws IOException
     */
    @Override
    public void exprotUserInfoExcel(HttpServletResponse response,List<TbUser> tbUsers) throws IOException {
        //写入Excel文件
        String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excal");
        response.addHeader("Content-Disposition","attachment;filename="+exportFileName);
        EasyExcel.write(response.getOutputStream(),TbUser.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(tbUsers);

    }


    /**
     * 导入用户信息
     * @param file
     * @throws IOException
     */
    @Override
    public void impeotUserInfoExcel(MultipartFile file) throws IOException {
        /*这里省略excel文件效验*/

        /*读取excel数据*/
        DataEasyExcelListener<TbUser> listener = new DataEasyExcelListener<>();
        InputStream inputStream =file.getInputStream();
        EasyExcel.read(inputStream, TbUser.class, listener).sheet(0).doRead();
        List<TbUser> data = listener.getData();
        System.out.println("导入用户信息");
        System.out.println(data);
        /*这里省略数据存取*/
        data.forEach(TbUser->{
            this.baseMapper.insert(TbUser);
        });
    }
}
